#include "FileBrowser.h"
#include <dirent.h>
#include <fstream>
#include "Utils.h"
/*---------------------------------------------------------------------------*/
FileBrowser::FileBrowser(char *path)
{
	string strpath = path;
	rootNode = new FileNode((char*)"");
	currentNode = rootNode->add(strpath);
}
/*---------------------------------------------------------------------------*/
FileBrowser::~FileBrowser()
{
	delete rootNode;
}
/*---------------------------------------------------------------------------*/
FileNode *FileBrowser::getRootNode()
{
	return rootNode;
}
/*---------------------------------------------------------------------------*/
FileNode *FileBrowser::getCurrentNode()
{
	return currentNode;
}
/*---------------------------------------------------------------------------*/
void FileBrowser::fillNode(FileNode *fn, int level, bool forced)
{
	DEBUGMSG("FileBrowser::fillNode() : " << fn->getAbsolutePath() << ( fn->isFilled() ? " " : " (new)" ));
	// if it's ..
	if( !fn->getName().compare("..") ) return;
	
		
	DIR 		*path = opendir( fn->getAbsolutePath().c_str() );
	dirent 		*pfile = NULL;
	
	// if it's root
	if( !fn->getParent() ) path = opendir( "/" );
		
			
	// if already filled		
	// TODO : next line is deprecated! it disables child nodes filling
	if( !forced && fn->isFilled() ) return ;	
	
	
	fn->setDone(true);
	
	// If not directory or already visited
	if( !path ) return;
	
	
	// if forced, delete children first (to avoid ghost files)
	if( forced ) fn->clear();

	
	while ( ( pfile = readdir(path) ) ) 
	{
		
		string str = pfile->d_name;
		int type = pfile->d_type;
		
		if( str.compare(".") && str.compare("..") )
		{
		
			
			FileNode *fn2 = fn->getChild(str);
			if( fn2 == NULL ) 
			{
				// add the child to his parent
				fn2 = new FileNode(str,fn);
				fn->addChild(fn2);
				
				fn2->setType(type);
				
				// TODO : add here other information about the filenode (size, ext, type)
				if(type == 8 ) getFileSize(fn2);
				
			}
	
			
			
			if(level > 1 || level < 0) fillNode(fn2, level -1);
		}
		
	}
	

}
/*---------------------------------------------------------------------------*/
void FileBrowser::fillCurrentNode(int level)
{
	fillNode(currentNode,level);
}
/*---------------------------------------------------------------------------*/
FileNode *FileBrowser::addPath(char *directory)
{
	return rootNode->add(directory);
}
/*---------------------------------------------------------------------------*/
void FileBrowser::goToPath(char *directory)
{
	currentNode = rootNode->add(directory);
}
/*---------------------------------------------------------------------------*/
void FileBrowser::getFileSize(FileNode *fn)
{
	ifstream is;
	unsigned long int length;
	string fullpath = fn->getAbsolutePath();
	is.open ( fullpath.c_str(), ios::binary );
	is.seekg (0, ios::end);
	length = is.tellg();
	is.close();
	
	fn->setSize(length);
}
/*---------------------------------------------------------------------------*/




